import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/index';
import { Button, Balloon } from '@teamix/ui';
import {
  Header,
  Content,
  OperationBar,
  YunxiaoIcon,
  YunxiaoTable,
} from '@alife/devops-ui';
import { enterPage, Perf } from 'utils/track';
import utils from 'utils';
import docs from 'utils/docs';
import { getFeature } from 'utils/features';
import intl from 'locale';
import MemberWithInvite from 'components/memberWithInvite';
import DeleteAdminPopConfirm from './deleteAdminPopConfirm';
import SyncAdminSwitch from './syncAdminSwitch';
import './index.scss';
// id通过force取得

const { id } = window.FORCE.organization;
const ACCESS_LEVELS = [
  {
    value: 60,
    label: intl.get({
      id: 'code-assets.admins.containers.root.CodeupEnterpriseAdministrator',
      defaultMessage: 'Codeup 企业管理员',
    }),
    // 手动添加的
  },
  {
    value: 70,
    label: intl.get({
      id: 'code-assets.admins.containers.root.EnterpriseOwner',
      defaultMessage: '云效企业拥有者',
    }),
  },
];

const getLabel = (value, record, arr) => {
  let label = intl.get({
    id: 'code-assets.admins.containers.root.CodeupEnterpriseAdministrator',
    defaultMessage: 'Codeup 企业管理员',
  });

  arr &&
    arr.forEach((item) => {
      if (item.value === value) {
        label = item.label;
      }
    });
  return label;
};

class Root extends Component {
  static propTypes = {
    adminList: PropTypes.arrayOf(PropTypes.object),
    isLoadingTable: PropTypes.bool,
  };

  static defaultProps = {
    adminList: [],
    isLoadingTable: false,
  };

  componentDidMount() {
    document.title = intl.get({
      id: 'code-assets.admins.containers.root.AdministratorSettingsCloudEffectCodeup',
      defaultMessage: '管理员设置 · 云效 Codeup',
    });

    this.props.getList(id);
    this.props.getAdminSetting();

    enterPage('Organization-Settings-Admins', {
      sendPerf: false,
    });
  }

  onSelectMember = (users) => {
    const formData = {};
    formData.tb_user_id = users.map((item) => item._userId);
    formData.access_level = 60;
    this.props.addOneAdmin(formData);
  };

  renderAccess = (value, index, record) => {
    return getLabel(value, record, ACCESS_LEVELS);
  };

  renderActions = (value, index, record) => {
    const isOrgOwner = this.isOrgOwner();
    return <DeleteAdminPopConfirm record={record} isOrgOwner={isOrgOwner} {...this.props} />;
  };

  renderTime = (value) => {
    return utils.getBeautyTime(value);
  };

  switchSyncAdmins = (value) => {
    this.props.updateAdminSetting(value);
  };

  // 当前用户是不是云效企业拥有者
  isOrgOwner = () => {
    const { adminList } = this.props;
    const curUser = window.FORCE.user;
    if (adminList && adminList.length && curUser) {
      return adminList.some((item) => {
        return curUser.id === item.tb_user_id && item.access_level === 70;
      });
    }
    return false;
  };

  render() {
    const { isLoadingTable, adminList, isGetSetting, auto_sync_member_enable } = this.props;
    const isOrgOwner = this.isOrgOwner();
    const hideTip =
      isLoadingTable ||
      adminList.findIndex((item) => {
        return item.access_level === 70;
      }) > -1;
    return (
      <>
        <Header
          title={intl.get({
            id: 'code-assets.admins.containers.root.AdministratorSettings',
            defaultMessage: '管理员设置',
          })}
          description={intl.get({
            id: 'code-assets.admins.containers.root.AdministratorsCanAccessAllRepositories.1',
            defaultMessage: '管理员可以访问所有仓库，具备代码库读写权限，并且可以管理所有功能',
          })}
        />
        <div className={`no-org-owner-tip ${hideTip ? '' : 'show-no-org-owner-tip'}`}>
          {intl.get({
            id: 'code-assets.admins.containers.root.TheOwnerOfTheEnterprise',
            defaultMessage: '企业拥有者已退出云效企业，请',
          })}

          <a href={docs('submit-work-order')} target="_blank" rel="noreferrer">
            {intl.get({
              id: 'code-assets.admins.containers.root.SubmitATicket',
              defaultMessage: '提交工单',
            })}
          </a>
          {intl.get({
            id: 'code-assets.admins.containers.root.ModifyAnEnterpriseOwner',
            defaultMessage: '修改企业拥有者',
          })}
        </div>
        <OperationBar>
          <div className="sync-admin-subtitle" style={{ position: 'relative' }}>
            {getFeature('organization.setting.adimin_setting.auto_sync_member') ?
              <SyncAdminSwitch
                onChange={(value) => {
                  this.switchSyncAdmins(value);
                }}
                isOrgOwner={isOrgOwner}
                isGetSetting={isGetSetting}
                auto_sync_member_enable={auto_sync_member_enable}
              />
            :
              <span> </span>
            }
            <span
              className="org-add-member-btn"
            >
              {isOrgOwner ? (
                <MemberWithInvite
                  trigger={
                    <Button type="primary" text>
                      <YunxiaoIcon type="add-fill" />
                      {intl.get({
                        id: 'code-assets.admins.containers.root.AddAdministrator',
                        defaultMessage: '添加管理员',
                      })}
                    </Button>
                  }
                  value={adminList.map((item) => {
                    item._userId = item.tb_user_id;
                    return item;
                  })}
                  title={intl.get({
                    id: 'code-assets.admins.containers.root.AddAdministrator',
                    defaultMessage: '添加管理员',
                  })}
                  multiple
                  mode="add"
                  autoFocus
                  onChange={this.onSelectMember}
                />
              ) : (
                <Balloon.Tooltip
                  popupContainer={(trigger) => trigger.parentNode}
                  trigger={
                    <Button type="primary" text disabled>
                      <YunxiaoIcon type="add-fill" />
                      {intl.get({
                        id: 'code-assets.admins.containers.root.AddAdministrator',
                        defaultMessage: '添加管理员',
                      })}
                    </Button>
                  }
                  align="l"
                >
                  {intl.get({
                    id: 'code-assets.admins.containers.root.YouAreNotAuthorizedTo',
                    defaultMessage: '无操作权限，请联系企业拥有者处理',
                  })}
                </Balloon.Tooltip>
              )}
            </span>
          </div>
        </OperationBar>

        <Content>
          <YunxiaoTable hasBorder dataSource={adminList} loading={isLoadingTable}>
            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.admins.containers.root.User',
                defaultMessage: '用户',
              })}
              dataIndex="name"
            />
            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.admins.containers.root.Role',
                defaultMessage: '角色',
              })}
              dataIndex="access_level"
              cell={this.renderAccess}
            />
            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.admins.containers.root.LastLogonTime',
                defaultMessage: '上次登录时间',
              })}
              dataIndex="last_sign_in_at"
              cell={this.renderTime}
            />
            <YunxiaoTable.Column
              title={intl.get({
                id: 'code-assets.admins.containers.root.Operation',
                defaultMessage: '操作',
              })}
              dataIndex="actions"
              cell={this.renderActions}
            />
          </YunxiaoTable>
          <Perf page="Organization-Settings-Admins" />
        </Content>
      </>
    );
  }
}

export default connect(
  (state) => state.organization.settings.admins,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
